package com.agent.service.mail.impl;

import com.agent.service.mail.MailService;
import com.agent.util.MyPropertiesConfigurer;
import lombok.extern.slf4j.Slf4j;
import microsoft.exchange.webservices.data.core.enumeration.service.ConflictResolutionMode;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.core.service.item.Item;
import org.apache.commons.mail.util.MimeMessageParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.search.FlagTerm;
import java.io.IOException;
import java.util.*;

/**
 * Created by hg on 2019/1/30.
 */
@Slf4j
@Service
@EnableScheduling
public class MailServiceImpl implements MailService {

    @Autowired
    RepaireInfoBiz repaireInfoBiz;
    String imapServer = MyPropertiesConfigurer.ctxPropertiesMap.get("mail.imapServer");
    String protocol = MyPropertiesConfigurer.ctxPropertiesMap.get("mail.protocol");
    String username = MyPropertiesConfigurer.ctxPropertiesMap.get("mail.username");
    String password = MyPropertiesConfigurer.ctxPropertiesMap.get("mail.password");

    Folder getFolder() throws MessagingException {
        // 定义连接POP3服务器的属性信息
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol); // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.imap.host", imapServer); // 发件人的邮箱的 SMTP服务器地址
//        props.setProperty("mail.imaps.usesocketchannels", "true");
        props.setProperty("mail.imap.usesocketchannels", "true");
        // 获取连接
        Session session = Session.getInstance(props, null);
        // 获取Store对象
        Store store = session.getStore(protocol);
        store.connect(imapServer, username, password); // POP3服务器的登陆认证
        Folder folder = store.getFolder("INBOX");// 获得用户的邮件帐户
        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限
        return folder;
    }





//    @Scheduled(cron = "0 0/1 9-18 * * *")
    @Override
    public void receiveMail() throws MessagingException, IOException {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if((date.getHours() > 17 && date.getMinutes() >= 30) || week == 1 || week ==7){
            return;
        }
        try (Folder folder = getFolder()) {
            FlagTerm ft =
                    new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false代表未读，true代表已读
            Message[] messages = folder.search(ft);// 得到邮箱帐户中的所有未读邮件
            for (Message message : messages) {
                try {
                    MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse();
                    String from = parser.getFrom(); // 获取发件人地址
                    List<Address> to = parser.getTo(); // 获取收件人地址
                    String subject = parser.getSubject(); // 获取邮件主题
//                    if(subject !=null && subject.contains("报修")){
                        String plainContent = parser.getPlainContent(); // 获取纯文本邮件内容（注：有些邮件不支持html）
                        log.info("receive mail from is {}, to is {},subject is {} plainContent is {}", new String[]{from, to.get(0).toString(), subject, plainContent});
                        repaireInfoBiz.insertByEmail(plainContent,from);
//                    }
                } catch (Exception e) {
                    log.error("javax.mail.event.MessageCountAdapter.messagesAdded error | ", e);
                }
            }
            folder.setFlags(messages, new Flags(Flags.Flag.SEEN),true);
        } catch (MessagingException exception) {
            log.error("com.agent.service.mail.impl.MailServiceImpl.receiveMail error |", exception);
        }
    }



//    @Scheduled(cron = "0 0/1 * * * *")
    // 0 */1 * * * ?
    @Scheduled(cron = "0 */1 9-18 * * ?")
    public void receiveExchangeMail() throws Exception {
        log.info("com.agent.service.mail.impl.MailServiceImpl.receiveExchangeMail start ......");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if((date.getHours() > 17 && date.getMinutes() >= 30) || week == 1 || week ==7){
            return;
        }
        ArrayList<Item> items = ExchangeMail.GetUnreadEmails();
        log.info("mail item size is {}",items.size());
        for(Item item:items){
            if (item.getSubject() != null ) {
                item.load();
                EmailMessage emailMessage = (EmailMessage) item;
                String from = emailMessage.getFrom().getAddress();
//                String htmlContent = emailMessage.getBody().toString();
                emailMessage.setIsRead(true);
                emailMessage.update(ConflictResolutionMode.AlwaysOverwrite);
//                String plainContent = parseHtmlContent(htmlContent);
                String subject = emailMessage.getSubject();
                log.info("from is "+from+" subject is :"+subject);
                repaireInfoBiz.insertByEmail(subject,from);
            }
        }
        log.info("com.agent.service.mail.impl.MailServiceImpl.receiveExchangeMail end ......");
    }

    private String parseHtmlContent(String htmlContent) {
        if(StringUtils.isEmpty(htmlContent)){
            return "";
        }
        Document document = Jsoup.parse(htmlContent);
        String content = document.select("body").text();
        if(content.contains(" ")){
            return content.split(" ")[0];
        }
        return content;
    }


}
